package com.pg.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pg.auth.model.dto.sysuser.SysUserConvertor;
import com.pg.auth.model.dto.sysuser.SysUserDTO;
import com.pg.auth.model.dto.sysuser.SysUserReq;
import com.pg.auth.model.dto.sysuser.SysUserVO;
import com.pg.auth.model.entity.SysUser;
import com.pg.auth.model.mapper.SysUserMapper;
import com.pg.auth.service.SysRoleUserService;
import com.pg.auth.service.SysUserService;
import com.pg.base.component.PageVO;
import com.pg.base.component.Pager;
import com.pg.base.enums.DeleteEnum;
import com.pg.base.util.PgSecretUtil;
import com.pg.base.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/***
 * SysUserServiceImpl
 * @author : huhuaping
 * @Date : 2024-06-06 20:59:34
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysUserServiceImpl implements SysUserService {

    @Value("${user.password.salt}")
    private String salt;

    private final SysUserMapper sysUserMapper;

    private final SysRoleUserService sysRoleUserService;

    @Override
    public PageVO<SysUserVO> page(Pager<SysUserReq, SysUserVO> pageReq){

        QueryWrapper<SysUser> queryWrapper = baseQueryWrapper(pageReq.getParam());

        PageVO<SysUserVO> result = sysUserMapper.selectByPage(pageReq.getPageVO(),pageReq.getParam());
        return result;
    }

    @Override
    public List<SysUserVO> list(SysUserReq sysUserReq){

        QueryWrapper<SysUser> queryWrapper = baseQueryWrapper(sysUserReq);

        List<SysUser> sysUserList = sysUserMapper.selectList(queryWrapper);

        return SysUserConvertor.INSTANCE.listDbToVO(sysUserList);

    }

    @Override
    public SysUserVO getById(Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        return SysUserConvertor.INSTANCE.dbToVO(sysUser);
    }

    @Override
    public Long add(SysUserDTO sysUserDTO,LoginVO userVo) {

        log.info("add sysUser [{}]，op user[{}]", JSON.toJSONString(sysUserDTO),JSON.toJSONString(userVo));
        SysUser sysUserAdd = SysUserConvertor.INSTANCE.dtoToDB(sysUserDTO);

        if (null != sysUserAdd.getPassword()) {
            sysUserAdd.setPassword(PgSecretUtil.md5BySalt(sysUserAdd.getPassword(), salt));
        }

        sysUserMapper.insert(sysUserAdd);

        // 保存用户和角色的关系
        sysRoleUserService.save(sysUserAdd.getUserId(), Collections.singletonList(sysUserDTO.getRoleId()),userVo);

        return sysUserAdd.getUserId();
    }

    @Override
    public Integer updateById(SysUserDTO sysUserDTO,LoginVO userVo) {

        log.info("update sysUser [{}]，op user[{}]", JSON.toJSONString(sysUserDTO),JSON.toJSONString(userVo));

        SysUser sysUserAdd = SysUserConvertor.INSTANCE.dtoToDB(sysUserDTO);
        int count = sysUserMapper.updateById(sysUserAdd);

        // 保存用户和角色的关系
        sysRoleUserService.save(sysUserAdd.getUserId(), Collections.singletonList(sysUserDTO.getRoleId()),userVo);

        return count;
    }

    @Override
    public int deleteById(Long userId) {

        log.info("delete sysUser [{}]", userId);

        SysUser sysUser = sysUserMapper.selectById(userId);

        // 封装对象
        SysUser sysUserDelete = new SysUser();

        sysUserDelete.setUserId(userId);
        sysUserDelete.setDeleteStatus(DeleteEnum.DELETE.getValue());

        return sysUserMapper.updateById(sysUserDelete);

    }


    private QueryWrapper<SysUser> baseQueryWrapper(SysUserReq sysUser) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SysUser> lambda =  queryWrapper.lambda();
        lambda.eq(SysUser::getDeleteStatus,DeleteEnum.NORMAL.getValue());
            lambda.orderByDesc(SysUser::getUserId);
        if (ObjectUtil.isNotEmpty(sysUser.getUserId())) {
            lambda.eq(SysUser::getUserId, sysUser.getUserId());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getUserName())) {
            lambda.eq(SysUser::getUserName, sysUser.getUserName());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getPassword())) {
            lambda.eq(SysUser::getPassword, sysUser.getPassword());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getNickName())) {
            lambda.eq(SysUser::getNickName, sysUser.getNickName());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getRealName())) {
            lambda.eq(SysUser::getRealName, sysUser.getRealName());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getUserStatus())) {
            lambda.eq(SysUser::getUserStatus, sysUser.getUserStatus());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getOnlineStatus())) {
            lambda.eq(SysUser::getOnlineStatus, sysUser.getOnlineStatus());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getMobile())) {
            lambda.eq(SysUser::getMobile, sysUser.getMobile());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getEmail())) {
            lambda.eq(SysUser::getEmail, sysUser.getEmail());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getSource())) {
            lambda.eq(SysUser::getSource, sysUser.getSource());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getAppUserType())) {
            lambda.eq(SysUser::getAppUserType, sysUser.getAppUserType());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getLastLoginTime())) {
            lambda.eq(SysUser::getLastLoginTime, sysUser.getLastLoginTime());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getUserPicUrl())) {
            lambda.eq(SysUser::getUserPicUrl, sysUser.getUserPicUrl());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getIdCardType())) {
            lambda.eq(SysUser::getIdCardType, sysUser.getIdCardType());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getIdCardNo())) {
            lambda.eq(SysUser::getIdCardNo, sysUser.getIdCardNo());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getRemark())) {
            lambda.eq(SysUser::getRemark, sysUser.getRemark());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getTenantId())) {
            lambda.eq(SysUser::getTenantId, sysUser.getTenantId());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getOrgId())) {
            lambda.eq(SysUser::getOrgId, sysUser.getOrgId());
        }

        return queryWrapper;
    }

}
